from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from fdfs_client.client import Fdfs_client

from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb

# client = Fdfs_client('utils/fastdfs/client.conf')
# client.upload_by_filename('/home/python/Desktop/images/300090.jpg')
from utils.response_code import RETCODE


class ListView(View):
    def get(self,request,category_id,page_num):
        try:
            category=GoodsCategory.objects.get(id=category_id)      # category 是id为那个的商品类别名字
        except:
            return http.HttpResponseBadRequest('category_id is does not exist')

        sort = request.GET.get('sort')

        if sort == 'default':
            sort_filed='-create_time'
        elif sort == 'price':
            sort_filed='price'
        else:
            sort_filed='-sales'
        # 这个类别的所有商品信息
        skus = SKU.objects.filter(category=category).order_by(sort_filed)
        # 查询面包屑导航
        breadcrumb=get_breadcrumb(category)

        from django.core.paginator import Paginator
        # 创建分页类实例
        paginator = Paginator(object_list=skus, per_page=5)
        # 获取指定页数
        page_skus = paginator.page(page_num)
        # 得到总页数
        total_page = paginator.num_pages

        # 渲染页面
        context={
            'breadcrumb':breadcrumb,
            'sort': sort,  # 排序字段
            'category': category,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
        }
        return render(request,'list.html',context)

# 热销的展示
class HotView(View):
    def get(self,request,category_id):
        # 0. 判断分类数据是否正确
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '暂时无次分类'})
        # 1.根据分类来获取数据,并进行排序,排序之后获取前2条

        skus = SKU.objects.filter(category=category).order_by('-sales')[:2]

        # 2.将对象列表转换为字典
        skus_list = []
        for sku in skus:
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': skus_list})


from django import http
from django.shortcuts import render
from django.views import View
from apps.contents.utils import get_categories
from apps.goods.models import SKU, GoodsCategory
from apps.goods.utils import get_breadcrumb
from utils.response_code import RETCODE

# 商品详情页面
class DetailView(View):

    def get(self,request,sku_id):

        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }

        return render(request,'detail.html',context)



# 访问量
class VisitCountView(View):
    def post(self,request,category_id):
        # 校验是否有此类别的商品
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code':RETCODE.NODATAERR,'errmsg':'没有此分类商品'})
        from django.utils import timezone
        today=timezone.localdate()
        # 查询是否有此类别的通过即
        try:
            gvc=GoodsVisitCount.objects.get(category=category,
                                        date=today)
        # 如果没有此类别的统计,就创建一个,
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(category=category,
                                           date=today,
                                           count=1)
        # 如果有此类别的统计,就count+1
        else:
            gvc.count += 1
            gvc.save()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})
